<?php
    include_once "classes/User.php";
    session_start();
    include_once "session.php";
    if (!isLoggedIn()) {
        exit();
    }
    include_once("db/db_cse305.php");
    
    $OverwriteUserID =  $_SESSION['User']->UserID;
    if ($_SESSION['User']->UserType == "Representative" || $_SESSION['User']->UserType == "Manager") {
        if (isset($_POST["userid"])) {
            $OverwriteUserID = $_POST["userid"];
            if (!is_numeric($OverwriteUserID)) {
                exit();
            }
        } else {
            exit();
        }
    }
    
    $query = sprintf("SELECT * FROM accounts JOIN accountholdings USING (AccountID) JOIN stocks USING (StockSymbol) WHERE CustomerUserID = %d", mysql_real_escape_string($OverwriteUserID));
    $result = mysql_query($query) or die(mysql_error());
    $stockAccounts = array();
    while ($row = mysql_fetch_array($result)) {
        $acc = null;
        if (!array_key_exists($row["AccountID"], $stockAccounts)) {
            $acc = array();
            $acc["AccountID"] = $row["AccountID"];
            $acc["DateOpened"] = $row["DateOpened"];
            $acc["Holdings"] = array();
            $stockAccounts[$row["AccountID"]] = $acc;
        } else {
            $acc = $stockAccounts[$row["AccountID"]];
        }
        $stockAcc = $acc["Holdings"];
        $stock = array();
        $stock["StockSymbol"] = $row["StockSymbol"];
        $stock["StockName"] = $row["StockName"];
        $stock["Shares"] = $row["NumShares"];
        $stock["SharePrice"] = $row["SharePrice"];
        $stockAcc[] = $stock;

        //PHP makes the changes on COPIES of the objects. So stupid. Copy them back.
        $acc["Holdings"] = $stockAcc;
        $stockAccounts[$row["AccountID"]] = $acc;
    }
    
    foreach ($stockAccounts as $accID => $acc) {
        
        $query = sprintf("SELECT * FROM orders JOIN users ON (users.UserId = orders.EmployeeID) WHERE orders.AccountID = %d ORDER BY Time DESC, OrderID", $accID);
        $result = mysql_query($query) or die(mysql_error());
        $orders = array();
        while ($row = mysql_fetch_array($result)) {
            if (!array_key_exists($row["OrderID"], $orders)) {
                $order = array();
                $order["StockSymbol"] = $row["StockSymbol"];
                $order["OrderType"] = $row["OrderType"];
                
                $transactHist = array();
                $transact = array(
                    "TransactionID" => $row["OrderRowID"], 
                    "NumShares" => $row["NumShares"], 
                    "PriceType" => $row["PriceType"]
                );
                if (is_numeric($row["PriceType"])) {
                    $transact["Percentage"] = $row["Percentage"];
                }
                $transact["Fee"] = $row["Fee"];
                $transact["EmployeeID"] = $row["EmployeeID"];
                $transact["EmployeeName"] = $row["FirstName"] . " " . $row["LastName"];
                $transact["Time"] = $row["Time"];
                
                //$order["Time"] = $row["Time"];//Comment out if needed - Pull latest transaction time
                
                $transactHist[] = $transact;
                $order["TransactionHistory"] = $transactHist;
                $orders[$row["OrderID"]] = $order;
            } else {
                $order = $orders[$row["OrderID"]];
                $transactHist = $order["TransactionHistory"];
                $transact = array(
                    "TransactionID" => $row["OrderRowID"], 
                    "NumShares" => $row["NumShares"], 
                    "PriceType" => $row["PriceType"]
                );
                if (!is_numeric($row["PriceType"])) {
                    $transact["Percentage"] = $row["Percentage"];
                }
                $transact["Fee"] = $row["Fee"];
                $transact["EmployeeID"] = $row["EmployeeID"];
                $transact["EmployeeName"] = $row["FirstName"] . " " . $row["LastName"];
                $transact["Time"] = $row["Time"];
                $transactHist[] = $transact;
                $order["TransactionHistory"] = $transactHist;
                $orders[$row["OrderID"]] = $order;
            }
        }
        
        
        $val = 0; $volume = 0;
        foreach ($acc["Holdings"] as $key => $stock) {
            $val += $stock["Shares"] * $stock["SharePrice"];
            $volume += $stock["Shares"];
        }
        $acc["Value"] = $val;
        $acc["Volume"] = $volume;
        $acc["Orders"] = $orders;

        //Copy it back.
        $stockAccounts[$accID] = $acc;
    }
    echo json_encode($stockAccounts);
?>